import AsyncStorage from '@react-native-async-storage/async-storage';

// 存储键名常量
export const STORAGE_KEYS = {
  AUTH_TOKEN: 'authToken',
  USER_DATA: 'userData',
  APP_SETTINGS: 'appSettings',
  THEME: 'theme',
  LANGUAGE: 'language',
} as const;

// 存储工具类
export class Storage {
  // 存储数据
  static async set(key: string, value: any): Promise<void> {
    try {
      const jsonValue = JSON.stringify(value);
      await AsyncStorage.setItem(key, jsonValue);
    } catch (error) {
      console.error('Storage set error:', error);
    }
  }

  // 获取数据
  static async get(key: string): Promise<any> {
    try {
      const jsonValue = await AsyncStorage.getItem(key);
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (error) {
      console.error('Storage get error:', error);
      return null;
    }
  }

  // 删除数据
  static async remove(key: string): Promise<void> {
    try {
      await AsyncStorage.removeItem(key);
    } catch (error) {
      console.error('Storage remove error:', error);
    }
  }

  // 清除所有数据
  static async clear(): Promise<void> {
    try {
      await AsyncStorage.clear();
    } catch (error) {
      console.error('Storage clear error:', error);
    }
  }

  // 获取所有键
  static async getAllKeys(): Promise<string[]> {
    try {
      return await AsyncStorage.getAllKeys();
    } catch (error) {
      console.error('Storage getAllKeys error:', error);
      return [];
    }
  }

  // 存储用户认证信息
  static async setAuthData(token: string, userData: any): Promise<void> {
    await Promise.all([
      this.set(STORAGE_KEYS.AUTH_TOKEN, token),
      this.set(STORAGE_KEYS.USER_DATA, userData),
    ]);
  }

  // 获取用户认证信息
  static async getAuthData(): Promise<{ token: string | null; userData: any }> {
    const [token, userData] = await Promise.all([
      this.get(STORAGE_KEYS.AUTH_TOKEN),
      this.get(STORAGE_KEYS.USER_DATA),
    ]);
    return { token, userData };
  }

  // 清除用户认证信息
  static async clearAuthData(): Promise<void> {
    await Promise.all([
      this.remove(STORAGE_KEYS.AUTH_TOKEN),
      this.remove(STORAGE_KEYS.USER_DATA),
    ]);
  }

  // 存储应用设置
  static async setAppSettings(settings: any): Promise<void> {
    await this.set(STORAGE_KEYS.APP_SETTINGS, settings);
  }

  // 获取应用设置
  static async getAppSettings(): Promise<any> {
    return await this.get(STORAGE_KEYS.APP_SETTINGS);
  }
}

export default Storage; 